﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;

using System.Diagnostics;

namespace TJDevHouse.BackupUtils.DirectoryUtils
{
	/// <summary>
	/// Copies a directory and its contents.
	/// </summary>
	public static class DirectoryCopier
	{
		/// <summary>
		/// Defines the name of the trace source for this assembly
		/// </summary>
		public const string TraceSourceName = "TJDevHouse.BackupUtils.DirectoryUtils";

		private static TraceSource _traceSource;

		/// <summary>
		/// The trace source to use for this assembly
		/// </summary>
		public static TraceSource TraceSource
		{
			get
			{
				if (_traceSource == null)
				{
					_traceSource = new TraceSource(TraceSourceName);
				}
				return _traceSource;
			}
		}

		public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
		{
			TraceSource.TraceEvent(TraceEventType.Verbose, 3, "Copying {0} to {1}", source.FullName, target.FullName);

			// Check if the target directory exists, if not, create it.
			if (target.Exists == false)
			{
				TraceSource.TraceEvent(TraceEventType.Verbose, 3, "Target directory does not exist, so creating {0}", target.FullName);
				try
				{
					target.Create();
				}
				catch
				{
					TraceSource.TraceEvent(TraceEventType.Error, 1, "Error creating directory so skipping copy: {0}", target.FullName);
					return;
				}
			}

			// Copy each file into it's new directory.
			foreach (FileInfo fi in source.GetFiles())
			{
				string targetFileName = Path.Combine(target.ToString(), fi.Name);

				TraceSource.TraceEvent(TraceEventType.Verbose, 3, "Copying {0} -> {1}", fi.FullName, targetFileName);

				try
				{
					fi.CopyTo(targetFileName, true);
				} catch
				{
					TraceSource.TraceEvent(TraceEventType.Error, 2, "Error performing copy: {0} -> {1}", fi.FullName, targetFileName);
				}
			}

			// Copy each subdirectory using recursion.
			foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
			{
				DirectoryInfo nextTargetSubDir =
					target.CreateSubdirectory(diSourceSubDir.Name);
				CopyAll(diSourceSubDir, nextTargetSubDir);
			}

		}

	}
}
